﻿@page "/Centre/Project/{Id?}"
@using iOSClub.Data
@using iOSClub.Data.DataModels
@using iOSClub.WebSite.Models
@using Markdig
@using Microsoft.EntityFrameworkCore
@inject IDbContextFactory<iOSContext> DbFactory
@inject NavigationManager Nav
@inject MessageService MessageService

<PageTitle>当前项目 : @Data.Title -iStaff</PageTitle>

<PageView Style="min-height: 100%" ContextStyle="margin: 20px;"
          FullScreen="true"
          OnDelete="@(() => Nav.NavigateTo("/Centre"))"
          Title="@($"当前项目 : {Data.Title}")">
    <Extra>
        @if (Member.IsAdmin())
        {
            <Button Type="@ButtonType.Primary" OnClick="@(() => Nav.NavigateTo($"/Centre/EditProject/{Id}"))">
                更改项目
            </Button>
        }
    </Extra>
    <Context>
        <Title Level="2">@Data.Title</Title>
        <Text Type="secondary">@($"{Data.StartTime} - {Data.EndTime}")</Text>
        <div style="margin-top: 10px">
            <Tag Icon="apple" Color="blue-inverse">@Data.Department?.Name</Tag>
        </div>
        <p>@((MarkupString)Markdown.ToHtml(Data.Description))</p>
        <Divider/>
        <Flex Justify="space-between">
            <Title Level="4">任务列表</Title>
            <Button type="@ButtonType.Primary" OnClick="@(() => OpenModal())">
                创建新任务
            </Button>
        </Flex>
        @if (Data.Tasks.Count == 0)
        {
            <Empty Image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg" Style="padding: 20px">
                <DescriptionTemplate>
                    <span>当前项目没有任务</span>
                </DescriptionTemplate>
                <ChildContent>
                    <Button type="@ButtonType.Primary" OnClick="@(() => OpenModal())">
                        创建一个？
                    </Button>
                </ChildContent>
            </Empty>
        }
        else
        {
            <AntList DataSource="@Data.Tasks" TItem="TaskModel">
                <ListItem>
                    <Extra>
                        <Space>
                            <SpaceItem>
                                <Button Type="@ButtonType.Link" OnClick="@(() => Done(context))">
                                    @(context.Status ? "未完成" : "完成")
                                </Button>
                            </SpaceItem>
                            <SpaceItem>
                                <Button Type="@ButtonType.Primary" OnClick="@(() => OpenModal(context))">
                                    编辑
                                </Button>
                            </SpaceItem>
                            <SpaceItem>
                                <Button Danger OnClick="@(() => Delete(context))">
                                    删除
                                </Button>
                            </SpaceItem>
                        </Space>
                    </Extra>
                    <ChildContent>
                        <ListItemMeta>
                            <TitleTemplate>
                                <Space Align="center" Size="@("large")">
                                    <SpaceItem>
                                        <h1>@context.Title</h1>
                                    </SpaceItem>
                                    <SpaceItem>
                                        <Icon Type="team"/>
                                        @context.Users.Count.ToString()
                                    </SpaceItem>
                                </Space>
                            </TitleTemplate>
                            <DescriptionTemplate>
                                <Text Type="secondary">@($"{context.StartTime} - {context.EndTime}")</Text>
                                <Tag Color="@TaskColor(context)">@TaskString(context)</Tag>
                            </DescriptionTemplate>
                        </ListItemMeta>
                    </ChildContent>
                </ListItem>
            </AntList>
        }
        <Divider/>
        <Flex Justify="space-between">
            <Title Level="4">项目成员</Title>
            <Button type="@ButtonType.Primary" OnClick="AddStaff">
                加入或邀请
            </Button>
        </Flex>

        @if (Data.Staffs.Count == 0)
        {
            <Empty Image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg" Style="padding: 20px">
                <DescriptionTemplate>
                    <span>当前项目没有成员</span>
                </DescriptionTemplate>
                <ChildContent>
                    <Button type="@ButtonType.Primary" OnClick="AddStaff">加入或邀请</Button>
                </ChildContent>
            </Empty>
        }
        else
        {
            <AntList DataSource="@Data.Staffs" TItem="StaffModel">
                <ListItem>
                    <ListItemMeta>
                        <AvatarTemplate>
                            <Avatar Style="background-color: #7265e6; vertical-align: middle;" Size="large">
                                @context.Name.First()
                            </Avatar>
                        </AvatarTemplate>
                        <TitleTemplate>
                            <h3>@context.Name</h3>
                        </TitleTemplate>
                        <DescriptionTemplate>
                            <p>@MemberModel.IdentityDictionary[context.Identity]</p>
                        </DescriptionTemplate>
                    </ListItemMeta>
                </ListItem>
            </AntList>
        }
    </Context>
</PageView>

<Modal @bind-Visible="@_visible" Footer="@null">
    <Form Model="TaskData"
          OnFinish="OnFinish" ValidateMode="FormValidateMode.Rules">
        <FormItem Class="item" Label="任务名称" Rules="@SignRecord.TaskTitleRules">
            <Input @bind-Value="@context.Title"/>
        </FormItem>
        <FormItem Class="item" Label="任务描述" Rules="@SignRecord.TaskDescriptionRules">
            <TextArea @bind-Value="@context.Description" ></TextArea>
        </FormItem>
        <FormItem Class="item" Label="任务开始时间">
            <DatePicker @bind-Value="@context.StartTime" Format="yyyy年MM月dd日" Mask="yyyy年MM月dd日"/>
        </FormItem>
        <FormItem Class="item" Label="任务结束时间">
            <DatePicker @bind-Value="@context.EndTime" Format="yyyy年MM月dd日" Mask="yyyy年MM月dd日"/>
        </FormItem>
        <FormItem Style="text-align: center">
            <Button Type="@ButtonType.Primary" HtmlType="submit">
                @if (!string.IsNullOrEmpty(TaskData.Id))
                {
                    <p>添加</p>
                }
                else
                {
                    <p>更改</p>
                }
            </Button>
        </FormItem>
    </Form>
</Modal>

@code {
    private TaskEditModel TaskData { get; set; } = new();
    private bool _visible;

    private void OpenModal()
    {
        _visible = true;
    }

    private void OpenModal(TaskModel task)
    {
        TaskData = TaskEditModel.FromTask(task);
        OpenModal();
    }

    private async Task OnFinish()
    {
        await using var context = await DbFactory.CreateDbContextAsync();
        var task = TaskData.ToTask();
        if (string.IsNullOrEmpty(TaskData.Id))
        {
            var p = await context.Projects.FirstOrDefaultAsync(x => x.Id.ToString() == Id);
            if (p == null)
            {
                await MessageService.Error("项目不存在");
                return;
            }

            task.Project = Data;
            var staff = await context.Staffs.FirstAsync(x => x.UserId == Member.UserId);
            task.Users.Add(staff);
            task.Id = DataTool.StringToHash(task.ToString());
            p.Tasks.Add(task);
            Data.Tasks.Add(task);
            await context.SaveChangesAsync();
            await MessageService.Success("添加成功");
        }
        else
        {
            var a = await context.Tasks.FirstOrDefaultAsync(x => x.Id == task.Id);
            if (a == null)
            {
                await MessageService.Error("任务不存在");
                return;
            }

            a.Update(task);
            await context.SaveChangesAsync();
            await MessageService.Success("更改成功");
            var t = Data.Tasks.First(x => x.Id == task.Id);
            t.Update(task);
            StateHasChanged();
        }

        _visible = false;
        TaskData = new TaskEditModel();
    }

    private async Task AddStaff()
    {
        if (Data.Staffs.Any(x => x.UserId == Member.UserId))
        {
            await MessageService.Error("你已经加入该项目");
            return;
        }

        await using var context = await DbFactory.CreateDbContextAsync();
        var a = await context.Projects.Include(projectModel => projectModel.Staffs).FirstOrDefaultAsync(x => x.Id.ToString() == Id);
        if (a == null)
        {
            await MessageService.Error("项目不存在");
            return;
        }

        var staff = await context.Staffs.FirstAsync(x => x.UserId == Member.UserId);

        if (a.Staffs.Any(x => x.UserId == Member.UserId))
        {
            await MessageService.Error("你已经加入该项目");
            return;
        }

        a.Staffs.Add(staff);
        await context.SaveChangesAsync();
        await MessageService.Success("添加成功");
        Data.Staffs.Add(staff);
        StateHasChanged();
        _visible = false;
    }

}

@code {
    [CascadingParameter] private MemberModel Member { get; set; } = new();
    [Parameter] public string? Id { get; set; }
    private ProjectModel Data { get; set; } = new();

    protected override async Task OnInitializedAsync()
    {
        if (Member.Identity == "Member")
        {
            Nav.NavigateTo("/Centre");
            return;
        }

        await using var context = await DbFactory.CreateDbContextAsync();

        var a = await context.Projects
            .Include(x => x.Department)
            .Include(x => x.Staffs)
            .Include(x => x.Tasks)
            .ThenInclude(x => x.Users)
            .FirstOrDefaultAsync(x => x.Id == Id);
        if (a == null)
        {
            await MessageService.Error("项目不存在");
            Nav.NavigateTo("/Centre");
            return;
        }

        Data = a;
        
        await base.OnInitializedAsync();
    }

    private static string TaskColor(TaskModel task)
    {
        var today = DateTime.Today;
        var start = DateTime.Parse(task.StartTime);
        var end = DateTime.Parse(task.EndTime);
        if (today > end) return "red-inverse";
        if (start > today) return "blue-inverse";
        return task.Status ? "#87d068" : "#2db7f5";
    }

    private static string TaskString(TaskModel task)
    {
        var today = DateTime.Today;
        var start = DateTime.Parse(task.StartTime);
        var end = DateTime.Parse(task.EndTime);
        if (today > end) return "超时未完成";
        if (start > today) return "未开始";
        return task.Status ? "已完成" : "正在进行";
    }

    private async Task Delete(TaskModel model)
    {
        await using var context = await DbFactory.CreateDbContextAsync();
        var a = await context.Tasks.FirstOrDefaultAsync(x => x.Id == model.Id);
        if (a == null)
        {
            await MessageService.Error("任务不存在");
            return;
        }

        context.Tasks.Remove(a);
        await context.SaveChangesAsync();
        await MessageService.Success("删除成功");
        Data.Tasks.Remove(model);
        StateHasChanged();
    }

    private async Task Done(TaskModel model)
    {
        await using var context = await DbFactory.CreateDbContextAsync();
        var a = await context.Tasks.FirstOrDefaultAsync(x => x.Id == model.Id);
        if (a == null)
        {
            await MessageService.Error("任务不存在");
            return;
        }

        a.Status = !model.Status;
        await context.SaveChangesAsync();
        await MessageService.Success("更改成功");
        model.Status = !model.Status;
        StateHasChanged();
    }

}

<style>
    h1,h2,h3{
        font-size: initial;
    }
</style>